package com.oo.chartlibrary.charts;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.RectF;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;

import com.oo.chartlibrary.R;

import java.util.ArrayList;

/**
 * Created by zhuxiaolong on 2017/12/18.
 * 饼状图
 * 设置数据  根据数据组分类 颜色 名称
 * 1、 基本背景圆形
 * 2、 各个部分 扇形 以及描边
 * 3、 点击反馈 选择的扇形部分 浮起 高亮
 * 4、 可调 饼图角度
 */

public class PieChartView extends View implements View.OnTouchListener {
    private final String TAG = getClass().getSimpleName();

    public PieChartView(Context context) {
        this(context, null);
    }

    public PieChartView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public PieChartView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        propertyInit(context, attrs, defStyleAttr);
    }

    private void propertyInit(Context context, AttributeSet attrs, int defStyleAttr) {
        TypedArray array = context.getTheme().obtainStyledAttributes(attrs, R.styleable.PieChartView, defStyleAttr, 0);
        itemTextSize = array.getDimensionPixelOffset(R.styleable.PieChartView_textSize, toPx(12));
        itemTextColor = array.getColor(R.styleable.PieChartView_textColor, Color.WHITE);
        array.recycle();

        itemPaint = new Paint();
        itemPaint.setStyle(Paint.Style.FILL_AND_STROKE);
        itemPaint.setAntiAlias(true);

        textPaint = new Paint();
        textPaint.setAntiAlias(true);
        textPaint.setTextAlign(Paint.Align.CENTER);
        textPaint.setColor(itemTextColor);
        textPaint.setTextSize(itemTextSize);

    }


    /*基本属性*/
    private ArrayList<ItemData> itemDataArrayList;

    //文字
    private int itemTextSize;
    private int itemTextColor;
    //饼图 线框 宽度
    private int lineWidth = 2;


    /*绘制属性*/
    //扇区画笔
    private Paint itemPaint;
    //文字画笔
    private Paint textPaint;
    //基本画笔
    private Paint basePaint;
    //视图中点
    private PointF viewCenter;
    //饼图 半径;
    private float radius;
    //绘制区域
    private RectF drawRect;

    /**
     * 动态尺寸转换
     */
    private int toPx(int fromDP) {
        float density = getContext().getResources().getDisplayMetrics().density;
        return (int) (density * fromDP + 0.5f);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// Try for a width based on our minimum
        int minw = getPaddingLeft() + getPaddingRight() + getSuggestedMinimumWidth();
        int w = resolveSizeAndState(minw, widthMeasureSpec, 1);

        // Whatever the width ends up being, ask for a height that would let the pie
        // get as big as it can
        int minh = MeasureSpec.getSize(w) + getPaddingBottom() + getPaddingTop();
        int h = resolveSizeAndState(MeasureSpec.getSize(w), heightMeasureSpec, 0);

        setMeasuredDimension(w, h);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        //获取视图尺寸 计算绘制区域
        Log.i(TAG, "onSizeChanged: ");
        /*计算圆心*/
        viewCenter = new PointF(w * 0.5f, h * 0.5f);
        /*计算绘制 基础圆rect*/
        //判断 形状
        int size = Math.min(w - getPaddingLeft() - getPaddingRight(), h - getPaddingTop() - getPaddingBottom());
        radius = (int) (size * 0.5f - itemTextSize + 0.5f);
        drawRect = new RectF(viewCenter.x - radius, viewCenter.y - radius
                , viewCenter.x + radius, viewCenter.y + radius);
        /*计算半径 安静跟文字有关 所以在 获取文字后才进行计算*/
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Log.i(TAG, "onDraw: ");
        drawArcs(canvas, itemDataArrayList);
    }

    private void drawArcs(Canvas canvas, ArrayList<ItemData> datas) {
        if (angles != null && angles.length > 0) {
            int currentAngle = startAngle;
            for (int i = 0; i < angles.length; i++) {
                Log.i(TAG, "drawArcs: from " + currentAngle + "  to " + (currentAngle + angles[i]));
                itemPaint.setColor(datas.get(i).color);
                canvas.drawArc(drawRect, currentAngle, angles[i], true, itemPaint);
                Log.i(TAG, "drawArcs: text position x:" + textPoints[i].x + "  y:" + textPoints[i].y);
                canvas.drawText(datas.get(i).dataName, textPoints[i].x, textPoints[i].y, textPaint);
                currentAngle += angles[i];
            }
        }
    }

    private int[] angles;
    private int startAngle = 0;
    private PointF[] textPoints;

    public void setItemDatas(ArrayList<ItemData> datas) {
        itemDataArrayList = datas;
        if (datas != null && datas.size() > 0) {
            int total = 0;
            angles = new int[datas.size()];
            textPoints = new PointF[datas.size()];
            for (int i = 0; i < angles.length; i++) {
                //计算总数
                total += datas.get(i).value;
            }
            //每块所占比例
            int currentAngle = startAngle;
            float px = 0;
            float py = 0;
            for (int i = 0; i < angles.length; i++) {
                //计算 每块区域的角度
                angles[i] = 360 * datas.get(i).value / total;
                //根据角度计算 每块区域的 文字位置
                px = (float) Math.cos(Math.toRadians(angles[i] * 0.5f + currentAngle)) * (radius +itemTextSize)+ viewCenter.x;
                py = (float) Math.sin(Math.toRadians(angles[i] * 0.5f + currentAngle)) * (radius+itemTextSize) + viewCenter.y;

                textPoints[i] = new PointF(px, py);
                currentAngle += angles[i];
            }


            invalidate();
        }
    }


    private void checkTouchArea(float x, float y) {

        int angle = 0;
    }


    @Override
    public boolean onTouch(View v, MotionEvent event) {
        boolean result = mGestureDetector.onTouchEvent(event);
        if (event.getAction() == MotionEvent.ACTION_DOWN) {

        }


        if (event.getAction() == MotionEvent.ACTION_MOVE) {

        }

        if (event.getAction() == MotionEvent.ACTION_UP) {

        }


        return result;
    }


    /**
     * 代表 饼图的数据块信息
     */
    public static class ItemData {
        private String dataName;
        private int color;
        private int value;

        public void setDataName(String dataName) {
            this.dataName = dataName;
        }

        public void setColor(int color) {
            this.color = color;
        }

        public void setValue(int value) {
            this.value = value;
        }
    }


    public static class MyGestureListener extends GestureDetector.SimpleOnGestureListener {
        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            return true;
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            return true;
        }
    }

    private GestureDetector mGestureDetector = new GestureDetector(getContext(), new MyGestureListener());


}
